<?php

namespace app\api\controller;

use app\admin\model\Market;
use app\api\model\Address as AddressModel;
use app\common\controller\Api;
use think\Db;

/**
 * 地址接口
 */
class Address extends Api
{
    //protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    //市场列表
    public function market()
    {
        $list = Market::order('createtime desc')->select();
        $this->success('',$list);
    }


    //省市区
    public function district()
    {
        $type = input('type',0);
        $parent_id = input('parent_id',0);
        $where = [];
        if ($type==0){
            $where['level'] = 'province';
        }
        if ($parent_id){
            $where['parent_id'] = $parent_id;
        }
        $provincelist = Db::name('district')->where($where)->select();
        $this->success('', $provincelist);
    }

    //地址列表
    public function lists()
    {
        $lists = AddressModel::where(['user_id'=>$this->auth->id])
            ->order('is_default desc createtime desc')->select();
        $this->success('请求成功',$lists);
    }

    //添加/编辑地址
    public function save()
    {
        try {
            $address_model = new AddressModel();
            $param = input();
            $param['user_id'] = $this->auth->id;
            $res = $address_model->add($param);

        } catch (\Exception $e) {

            $this->error($e->getMessage());
        }

        $this->success('',$res);
    }

    //设置默认地址
    public function setdefault()
    {
        $id = input('id',0);
        $info = AddressModel::get($id);
        if (!$info)$this->error('地址不存在');
        $info->is_default = 1;
        AddressModel::where(['user_id' => $this->auth->id])->update(['is_default'=>0]);
        $info->save();

        $this->success('设置成功');
    }

    //地址详情
    public function info()
    {
        $id = input('id',0);
        $info = AddressModel::get($id);
        if (!$info)$this->error('地址不存在');
        $market = Market::get($info['shop_id']);
        $info['serial_number'] = $market?$market['serial_number']:'';
        $this->success('',$info);
    }

    //删除地址
    public function del()
    {
        $id = input('id',0);
        $info = AddressModel::get($id);
        if (!$info)$this->error('地址不存在');
        $info->delete();
        $this->success('删除成功');
    }
}
